<?php
error_reporting(0);
header("Content-Type: application/json;chartset=uft-8");

require __DIR__ . '/vendor/autoload.php';
use Curl\Curl;

function getApiData($url, $method = 'GET', $datas = null, $headers = [], $cookies = []){
    $curl = new Curl();
    $curl->setHeaders($headers);
    $curl->setCookies($cookies);
    //比如GET，POST，PUT，DELETE, PATCH,OPTIONS,HEAD等方法
    call_user_func(array($curl, strtolower($method)),$url,$datas);

    if ($curl->error) {
        $output['code'] = $curl->errorCode;
        $output['msg'] = $curl->errorMessage;
    } else {
        $output['header'] = $curl->responseHeaders;
        $output['body'] = $curl->response;
        $output['detail'] = $curl->getInfo();
    }
    return $output;
}

//成功返回数据
function successData($msg, $data)
{
    echo json_encode([
        'code' => 200,
        'msg' => $msg,
        'data' => $data,
    ]);
    die;
}

//错误返回数据
function errorData($msg)
{
    echo json_encode([
        'code' => 500,
        'msg' => $msg,
    ]);
    die;
}

//通过POST传参过的数据，如果不是，直接返回异常
$postStr = file_get_contents('php://input');
$post = json_decode($postStr, true);
if(!$post){
    $post = $_POST;
}
if (!$post) {
    errorData('参数错误');
}

$url = $post['url'];
if (!$url) {
    errorData('请填写API请求地址');
}
$method = $post['method'] ?? 'GET';
$body = [];

$cookies = $post['cookies'] ?? [];

$type = $post['nowType'];
//表示在线diygwUI可视化调试，如果不是表示直接返回结果
if($type=='agent'){

    $params = $post['params'] ?? [];

    $contentType = $post['contentType'] ?? "application/json; charset=utf-8";

    foreach ($params as $param){
        if(!empty($param['key']) && !empty($param['value'])){
            $body[$param['key']] = $param['value'];
        }
    }
    $headers = $post['headers'] ?? [];
    $header = [];
    foreach ($headers as $param){
        if(!empty($param['key']) && !empty($param['value'])){
            $header[$param['key']] = $param['value'];
        }
    }


    if(empty($header['Content-Type'])){
        $header['Content-Type'] = $contentType."; charset=utf-8";
    }
    $contentType = $post['contentType'] ?? "application/json; charset=utf-8";
    $result = getApiData($url, $method, $body, $header, $cookies);
    echo successData('获取数据成功',$result);
}else{
    unset($post['method']);
    unset($post['url']);
    $body = $post;
    $header = $post['headers'] ;

    $result = getApiData($url, $method, $body, $header, $cookies);
    if($result && $result['code']){
        echo json_encode($result);
    }else if($result && is_string($result['body'])){
        echo $result['body'];
    }else{
        echo json_encode($result['body']);
    };

}


